const moment = require("moment");
const _ = require("lodash");
const { Descartes2SKU } = require("descartes-sku.js/dist");
const base = require("./../../base");

module.exports = class extends base {
    async _initialize() {
        await super.isCustomAuth();
        await super.isAppAuth();
        await super.isShopAuth();
    }

    /**
     *
     * @api {get} /shop/home/shop/product/product/index 商品列表
     * @apiDescription 商品列表
     * @apiGroup Shop/Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} AppToken 应用授权token.
     *
     * @apiParam {Number} group_id     分组id
     * @apiParam {Number} price_start  商品价格（开始）
     * @apiParam {Number} price_end    商品价格（结束）
     * @apiParam {String} keyword      商品名称
     * @apiParam {Number} page         页码
     *
     * @apiSampleRequest /shop/home/shop/product/product/index
     *
     */
    async index() {
        const {
            page = 1,
            keyword,
            group_id,
            price_start,
            price_end
        } = this.query;
        const shopId = this.state.shop.id;
        const product = await this.model("product")
            .query(qb => {
                qb.where("shop_product.shop_id", shopId);
                if (this.isSet(group_id)) {
                    qb.join(
                        "shop_productgroup_product",
                        "shop_productgroup_product.product_id",
                        "shop_product.id"
                    );
                    qb.where(
                        "shop_productgroup_product.group_id",
                        "=",
                        group_id
                    );
                    qb.whereNull("shop_productgroup_product.deleted_at");
                }
                if (this.isSet(keyword)) {
                    qb.where("shop_product.name", "like", "%" + keyword + "%");
                }
                if (this.isSet(price_start) && this.isSet(price_end)) {
                    qb.where("shop_product.price", ">=", price_start);
                    qb.where("shop_product.price", "<=", price_end);
                }
                qb.orderBy("shop_product.id", "desc");
            })
            .fetchPage({
                page: page,
                pageSize: 20,
                withRelated: [
                    "group.group",
                    {
                        sku: qb => {
                            qb.orderBy("shop_productsku.price", "asc");
                        }
                    }
                ]
            });
        this.success(product);
    }

    /**
     *
     * @api {post} /shop/home/shop/product/product/add 新增/修改商品
     * @apiDescription 新增/修改商品
     * @apiGroup Shop/Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} AppToken 应用授权token.
     *
     * @apiParam {Number} id          商品id
     * @apiParam {String} name        商品名称
     * @apiParam {String} subname     商品子名称
     * @apiParam {Number} price       商品价格
     * @apiParam {Number} price_org   商品原价
     * @apiParam {String} img_url     商品图片
     * @apiParam {String} album       商品图集
     * @apiParam {String} info        商品简介
     * @apiParam {String} groups      商品分组ids
     * @apiParam {Number} rank        商品排序
     * @apiParam {Number} sku_status  规格（1：开启，0：关闭）
     * @apiParam {Array}  sku_data    规格数据[{id 商品规格id,sku_ids 规格ids,sku_pids 规格pids, sku_names 规格名称集合, price 价格,price_org 原价,store 库存,status 状态}]
     * @apiParam {String} detail      商品详情
     * @apiParam {String} unit        商品单位
     * @apiParam {Number} status      活动状态（1：上架，0：下架）
     *
     * @apiSampleRequest /shop/home/shop/product/product/add
     *
     */
    async add() {
        const shopId = this.state.shop.id;
        const {
            id,
            name,
            subname,
            info,
            groups,
            album,
            img_url,
            rank,
            unit,
            price,
            price_org,
            sku_status,
            sku_data = [],
            detail,
            fee_type,
            fee_price,
            status
        } = this.post;

        const product = await this.model("product")
            .forge(
                Object.assign(
                    {
                        id,
                        name,
                        subname,
                        info,
                        img_url,
                        rank,
                        unit,
                        price,
                        price_org,
                        fee_type,
                        fee_price,
                        sku_status,
                        detail,
                        status
                    },
                    {
                        shop_id: shopId
                    }
                )
            )
            .save();

        const group = groups ? groups : [];
        const file = album ? album : [];

        // 规格
        await this.model("productsku")
            .query(qb => {
                qb.where("shop_id", shopId);
                qb.where("product_id", product.id);
            })
            .destroy();

        // 增加新数据
        const skuData = _.map(sku_data, value => {
            return Object.assign(
                {
                    sku_ids: value.sku_ids,
                    sku_pids: value.sku_pids,
                    price: value.price,
                    store: value.store
                },
                {
                    product_id: product.id,
                    shop_id: shopId
                }
            );
        });

        await doodoo.bookshelf.Collection.extend({
            model: this.model("productsku")
        })
            .forge(skuData)
            .invokeThen("save");

        // 分组
        if (group.length) {
            const producGroup = await this.model("productgroup_product")
                .query(qb => {
                    qb.where("shop_id", shopId);
                    qb.where("product_id", product.id);
                })
                .fetchAll();
            if (producGroup.length) {
                await this.model("productgroup_product")
                    .query(qb => {
                        qb.where("shop_id", shopId);
                        qb.where("product_id", product.id);
                    })
                    .destroy();
            }
            const productgroup = [];
            for (let i = 0; i < group.length; i++) {
                const productGroups = await this.model("productgroup")
                    .query(qb => {
                        qb.where("shop_id", shopId);
                        qb.where("name", group[i]);
                    })
                    .fetch();
                if (productGroups.id) {
                    productgroup.push({
                        shop_id: shopId,
                        product_id: product.id,
                        group_id: productGroups.id
                    });
                }
            }
            if (productgroup.length) {
                await doodoo.bookshelf.Collection.extend({
                    model: this.model("productgroup_product")
                })
                    .forge(productgroup)
                    .invokeThen("save");
            }
        }

        // 图集
        if (file.length) {
            const productalbum = await this.model("product_album")
                .query(qb => {
                    qb.where("shop_id", shopId);
                    qb.where("product_id", product.id);
                })
                .fetchAll();
            if (productalbum.length) {
                await this.model("product_album")
                    .query(qb => {
                        qb.where("shop_id", shopId);
                        qb.where("product_id", product.id);
                    })
                    .destroy();
            }
            const albums = [];
            for (let i = 0; i < file.length; i++) {
                albums.push({
                    shop_id: shopId,
                    product_id: product.id,
                    img_url: file[i]
                });
            }
            if (albums.length) {
                await doodoo.bookshelf.Collection.extend({
                    model: this.model("product_album")
                })
                    .forge(albums)
                    .invokeThen("save");
            }
        }
        this.success(product);
    }

    async getSku() {
        const { skuData } = this.post;
        const skuArray = [];
        for (const key in skuData) {
            skuArray.push(skuData[key].value);
        }

        const descartes = new Descartes2SKU(skuArray);
        const sku = descartes.descartes();
        sku.map((val, index) => {
            return val.join();
        });

        const skuRes = [];
        for (const key in sku) {
            const skus = await this.model("shop_sku")
                .query(qb => {
                    qb.whereIn("name", sku[key]);
                })
                .fetchAll();
            const skuIdsArray = [];
            const skuPidsArray = [];
            for (const key in skus) {
                skuIdsArray.push(skus[key].id);
                skuPidsArray.push(skus[key].pid);
            }

            skuRes.push({
                sku_ids: skuIdsArray.join(),
                sku_pids: skuPidsArray.join(),
                sku_name: sku[key].join(),
                price: 0,
                store: 0
            });
        }
        this.success(skuRes);
    }

    /**
     *
     * @api {get} /shop/home/shop/product/product/info 商品详情
     * @apiDescription 商品详情
     * @apiGroup Shop/Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} AppToken 应用授权token.
     *
     * @apiParam {Number} id     商品id
     *
     * @apiSampleRequest /shop/home/shop/product/product/info
     *
     */
    async info() {
        const { id } = this.query;
        const shopId = this.state.shop.id;
        const product = await this.model("product")
            .query(qb => {
                qb.where("id", id);
                qb.where("shop_id", shopId);
            })
            .fetch({ withRelated: ["album", "sku", "group.group"] });

        let skuIds = [];
        if (product.sku.length) {
            for (const item of product.sku) {
                skuIds = skuIds.concat(
                    item.sku_ids.split(","),
                    item.sku_pids.split(",")
                );
            }
        }
        const sku = await this.model("shop_sku")
            .query(qb => {
                qb.whereIn("id", skuIds);
            })
            .fetchAll();
        const skuTree = this.getTree(sku);
        const _skuData = [];
        for (const key in skuTree) {
            _skuData.push({
                name: skuTree[key].name,
                value: skuTree[key].sub.map(val => {
                    return val.name;
                })
            });
        }

        if (product.group.length) {
            product.groups = [];
            for (let i = 0; i < product.group.length; i++) {
                product.groups.push(product.group[i].group.name);
            }
        }
        this.success(Object.assign(product, { _skuData }));
    }

    /**
     *
     * @api {get} /shop/home/shop/product/product/update 商品状态
     * @apiDescription 商品状态
     * @apiGroup Shop/Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} AppToken 应用授权token.
     *
     * @apiParam {Number} id     商品ids
     * @apiParam {Number} status 商品状态
     *
     * @apiSampleRequest /shop/home/shop/product/product/update
     *
     */
    async update() {
        const { id, status } = this.query;
        const ids = id ? id.split(",") : [];
        const products = [];
        for (let i = 0; i < ids.length; i++) {
            const obj = { id: ids[i], status: status };
            products.push(obj);
        }
        const product = await doodoo.bookshelf.Collection.extend({
            model: this.model("product")
        })
            .forge(products)
            .invokeThen("save");
        this.success(product);
    }

    /**
     *
     * @api {get} /shop/home/shop/product/product/del 删除商品
     * @apiDescription 删除商品
     * @apiGroup Shop/Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} AppToken 应用授权token.
     *
     * @apiParam {Number} id     商品ids
     *
     * @apiSampleRequest /shop/home/shop/product/product/del
     *
     */
    async del() {
        const { id } = this.query;
        const ids = id ? id.split(",") : [];
        if (ids.length) {
            const product = await this.model("product")
                .query(qb => {
                    qb.whereIn("id", ids);
                })
                .destroy();
            this.success(product);
        }
    }
};
